package com.taotao.order.consumer;


import com.taotao.common.redis.service.RedisService;
import com.taotao.order.constants.OrderConstants;
import com.taotao.order.domain.Order;
import com.taotao.order.domain.request.OrderMessage;
import com.taotao.order.service.LuaService;
import com.taotao.order.service.OrderService;
import com.taotao.product.domain.SkuInventoryQuantity;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @className: OrderConsumer
 * @author: ZhangYuQi
 * @date: 2025/2/7 下午2:06
 * @Version: 1.0
 * @description:
 */

@Component
public class OrderConsumer {

    @Autowired
    private LuaService luaService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private OrderService orderService;

    @RabbitListener(queuesToDeclare = @Queue(name ="order.queue"))
    public void handleOrder(OrderMessage orderMessage) throws IOException {

        System.out.println("这是消费者");
        System.out.println("收到消息："+ orderMessage);

        //接收到消息 调用lua脚本对库存进行校验扣减
        boolean result = luaService.tryToBuy(orderMessage.getSkuIds(), orderMessage.getQuantitys());
        if(result){
            System.out.println("购买成功");
            //当前下单的所有sku库存全部充足后 扣减redis库存后开始生成订单
            //构建订单对象
            Order order = new Order();
            order.setOrderNum(orderMessage.getOrderNum());//订单号
            order.setUserId(orderMessage.getUserId());//下单人
            order.setOrderAddr(orderMessage.getOrderAddr());//下单地址
            order.setTotalMoney(orderMessage.getTotalMoney());//总金额
            order.setOrderStatus(1);//下单状态

            //将订单插入数据库 返回自增id
            orderService.insertOrder(order);

            //构建批量添加中间表对象
            // 创建结果列表
            List<SkuInventoryQuantity> skuOrders = new ArrayList<>();

            // 合并逻辑
            for (int i = 0; i < orderMessage.getSkuIds().size(); i++) {
                skuOrders.add(new SkuInventoryQuantity(String.valueOf(orderMessage.getSkuIds().get(i)), orderMessage.getQuantitys().get(i)));
            }

            //添加中间表
            orderService.insertSkuOrder(order.getId(),skuOrders);

            //下单成功 修改redis中的状态 告诉前端下单成功
            redisService.setCacheObject(OrderConstants.ORDER_STATUS + orderMessage.getOrderNum(), 1);
        }else{
            System.out.println("购买失败");
            //下单失败 修改redis中的状态 告诉前端下单失败
            redisService.setCacheObject(OrderConstants.ORDER_STATUS + orderMessage.getOrderNum(), 2);
        }

    }

}
